package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("PunishRestController")
public class PunishRestController extends CmiEmaController {

	/**
	 * Create a new Punish entity
	 * 
	 */
	@RequestMapping(value = "/newPunish", method = RequestMethod.POST)
	@ResponseBody
	public Object newPunish(@RequestBody Punish punish) {
		punishService.savePunish(punish);
		return JSONObject.parse(cmiPsonService.toJsonString(punishDAO.findPunishByPrimaryKey(punish.getId()), 2));
	}

	@RequestMapping(value = "/restNewPunish", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewPunish(@RequestBody String punishJson) {
		Punish punish = new Gson().fromJson(punishJson, Punish.class);
		appendReferences(punish);
		punishService.savePunish(punish);
		return JSONObject.parse(cmiPsonService.toJsonString(punishDAO.findPunishByPrimaryKey(punish.getId()), 2));
	}

	@RequestMapping(value = "/savePunish", method = RequestMethod.PUT)
	@ResponseBody
	public Punish savePunish(@RequestBody Punish punish) {
		punishService.savePunish(punish);
		return punishDAO.findPunishByPrimaryKey(punish.getId());
	}

	@RequestMapping(value = "/restSavePunish", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSavePunish(@RequestBody String punishJson) {
		Punish punish = new Gson().fromJson(punishJson, Punish.class);
		appendReferences(punish);
		CmiPsonService cmiPsonService = new CmiPsonService();
		punishService.savePunish(punish);
		return JSONObject.parse(cmiPsonService.toJsonString(punishDAO.findPunishByPrimaryKey(punish.getId()), 1));
	}

	@RequestMapping(value = "/restDeletePunish/{punishId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeletePunish(@PathVariable Integer punishId) {
		Punish punish = punishDAO.findPunishByPrimaryKey(punishId);
		punishService.deletePunish(punish);
	}

	@RequestMapping(value = "/restConfirmDeletePunishs")
	@ResponseBody
	public Object restConfirmDeletePunishs(@RequestBody Set<Integer> deletePunishsIds) {
		Set<Punish> deletePunishs = punishDAO.findPunishsByIds(deletePunishsIds);
		Set<Punish> referencedPunishs = punishService.loadReferencePunishs(deletePunishs);
		deletePunishs.removeAll(referencedPunishs);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedPunishs);
		jsonObject.put("deleteEntitys", deletePunishs);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeletePunishs")
	@ResponseBody
	public Object restDeletePunishs(@RequestBody Set<Punish> deletePunishs) {
		Iterator<Punish> iterator = deletePunishs.iterator();
		while (iterator.hasNext()) {
			Punish currentPunish = iterator.next();
			punishService.deletePunish(currentPunish);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listPunishs");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadPunish/{punishId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadPunish(@PathVariable Integer punishId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(punishDAO.findPunishByPrimaryKey(punishId), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadPunishEventpunishs/{punishId}/eventpunishs/{relatedeventpunishId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadPunishEventpunishs(@PathVariable Integer punishId, @PathVariable Integer relatedeventpunishId,
			@RequestBody CmiPagination cmiPagination) {
		Eventpunish eventpunish = eventpunishDAO.findEventpunishByPrimaryKey(relatedeventpunishId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(eventpunish, 2, cmiPagination));
	}

	public void appendReferences(Punish punish) {

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Eventpunish> eventpunishsForPunish = new HashSet<>();
		for (Eventpunish eventpunish_Punish : punish.getEventpunishsForPunish()) {
			eventpunishsForPunish.add(eventpunishService.findEventpunishByPrimaryKey(eventpunish_Punish.getId()));
		}
		punish.setEventpunishsForPunish(eventpunishsForPunish);
	}

	@RequestMapping(value = "/restGetPunishEventpunishs/{punishId}/eventpunishs", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetPunishEventpunishs(@PathVariable Integer punishId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(punishDAO.findPunishByPrimaryKey(punishId).getEventpunishsForPunish(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListPunishs", method = RequestMethod.GET)
	@ResponseBody
	public Object restListPunishs() {
		return JSONObject.parse(cmiPsonService.toJsonString(punishService.loadPunishs(), 2));
	}

	@RequestMapping(value = "/restListPunishsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListPunishsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = punishPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Punish> punishs = punishDAO.findAllPunishs(startResult, cmiPagination.getPaginationSize());
		String punishString = cmiPsonService.toPsonString(punishs, 2, cmiPagination);

		return JSONObject.parse(punishString);
	}

	@RequestMapping("/punishSelectBox")
	@ResponseBody
	public JSONObject punishSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键

			// 被引用键
			case "Eventpunish":
				entitySet = eventpunishService.loadEventpunishsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Eventpunish":
				entitySet = eventpunishDAO.findAllEventpunishs((pageNumber - 1) * paginationSize, paginationSize);
				count = eventpunishService.countEventpunishs();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Eventpunish":
				entitySet = eventpunishDAO.findEventpunishByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventpunishService.countEventpunishsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
